package com.hex.ds.em.hcdp.gauss.common.utils;


import com.github.vertical_blank.sqlformatter.SqlFormatter;
import com.github.vertical_blank.sqlformatter.languages.Dialect;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Package: com.hex.hdtp.scf.td.utils
 * @ClassName SqlFormatterUtil
 * @Description: sql格式化相关工具
 * @Author: Dong shiyi
 * @Date 2023/5/7 0:15
 * @Version v1.0
 **/
public class SqlFormatterUtil {

    public static String formatterSqlWithSpace(final String formatterBeforeSql) {
        String formatSql = formatterSql(formatterBeforeSql)
                //将“$ variable $” 替换成 "$variable$"
                .replaceAll("(\\$\\s)+(\\w+)(\\s\\$)+", "\\$$2\\$")
                .replaceAll("(\\$\\s\\{\\s)+(\\w+)(\\s\\})+", "\\$\\{$2\\}")
                //将字段注释移至字段后
                .replaceAll("(?m)([a-zA-Z_0-9)'])\\s*\\n\\s*(\\/\\*[^\\*]*?\\*\\/)", "$1    $2")
                //将“,”之前又换行符的进行去掉换行符
                .replaceAll("(,)(\\s*)", "$2$1")
//                .replaceAll("(?<=.)+([-(/\\*)]+)","----------------$1")
                //将 "| |" 变为 "||"
                .replaceAll("(\\|){1}(\\s{1})(\\|){1}", "$1$3")
                //针对于 "别名.空格多个" 的格式进行调整
                .replaceAll("(?<=[A-Za-z0-9])\\s*\\.\\s*", ".")
                .replaceAll("(?<=[A-Za-z0-9])_\\s+", "_")
                .replaceAll("\\s*>\\s*=\\s*", " >= ")
                .replaceAll("\\s*<\\s*=\\s*", " <= ")
                // 去除空白行
                .replaceAll("(?m)^[\\s\\t]*\\r?\\n", "");
        return removeSpacesInPlaceholders(formatSql);
    }

    public static String formatterSql(final String formatterBeforeSql) {
        return SqlFormatter.of(Dialect.PostgreSql).format(formatterBeforeSql).replaceAll(";", ";\n");
    }

    /**
     * @Method removeSpacesInPlaceholders
     * @Param
     * @param input
     * @Return java.lang.String
     * @Description 特殊处理-移除占位符中的空格$ { var: abc } -> ${var:abc}
     * @Author Wang zhihao
     * @Date 2024/2/4 15:24
     * @Version V1.0
     */
    public static String removeSpacesInPlaceholders(String input) {
        Pattern pattern = Pattern.compile("\\$\\s*\\{([^}]*)\\}");
        Matcher matcher = pattern.matcher(input);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String match = matcher.group(1);
            String replaced = match.replaceAll("\\s+", "");
            matcher.appendReplacement(result, "\\${" + replaced + "}");
        }
        matcher.appendTail(result);
        return result.toString();
    }
}
